package subject1.binarySearch;

/**
 * @Author CandyWall
 * @Date 2022/6/4--13:23
 * @Description 测试二分查找
 */
public class BinarySearchTest {
    // 测试闭区间二分查找
    public int binarySearch(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] == target) {
                return mid;
            }
        }
        return -1;
    }

    // 测试闭区间寻找左侧边界
    public int binarySearchLeftBound(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] >= target) {
                right = mid - 1;
            }
        }
        // 考虑边界情况
        if (left >= nums.length || nums[left] != target) {
            return -1;
        }
        return left;
    }

    // 测试闭区间寻找右侧边界
    public int binarySearchRightBound(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] <= target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        if (right < 0 || nums[right] != target) {
            return -1;
        }
        return right;
    }

    public static void main(String[] args) {
        BinarySearchTest binarySearchTest = new BinarySearchTest();
        System.out.println(binarySearchTest.binarySearch(new int[]{1, 2, 5, 8, 9}, 8));

        System.out.println(binarySearchTest.binarySearchLeftBound(new int[]{1, 2, 3, 3, 3, 3, 5, 8, 8}, 3));

        System.out.println(binarySearchTest.binarySearchRightBound(new int[]{1, 2, 3, 3, 3, 3, 5, 8, 8}, 3));
    }
}
